package com.fw.validator;

import cn.hutool.core.lang.Validator;
import com.fw.annotation.IsPhone;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.function.Function;
import java.util.function.Supplier;

public class IsMobileValidator implements ConstraintValidator<IsPhone,String> {

    private boolean flag;

    @Override
    public void initialize(IsPhone constraintAnnotation) {
            flag = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
        return isPass((thisPhone)->
            flag ? Validator.isMobile(thisPhone) : Boolean.TRUE
        ,()-> phone);
    }

    private boolean isPass(Function<String,Boolean> function, Supplier<String> stringSupplier){
        return function.apply(stringSupplier.get());
    }
}
